package com.evo.chat.common.base;

import com.evo.chat.common.ResultEnum;
import com.evo.chat.common.exception.ChatException;
import com.evo.chat.common.utils.RedisUtil;
import com.evo.chat.web.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author luwenzheng
 * date 2020-02-10
 */
public class BaseController {

    @Resource
    public RedisUtil redisUtil;

    @Autowired
    private HttpServletRequest httpServletRequest;


    /**
     * 验证token
     * @return
     */
    protected Integer verifyToken () {
        String authorization = httpServletRequest.getHeader("Authorization");
        System.out.println("token => " + authorization);

        if(StringUtils.isEmpty(authorization)){
            throw new ChatException(ResultEnum.USER_NOT_LOGIN);
        }
        Integer userId = (Integer) redisUtil.get(authorization);
        System.out.println("userId=> " + userId);

        if(userId == null){
            throw new ChatException(ResultEnum.USER_NOT_LOGIN);
        }
        return userId;
    }

    protected void loginVerify (String name, String password) {
        if(StringUtils.isEmpty(name)
                || StringUtils.isEmpty(password)){
            throw new ChatException(ResultEnum.PARAMETER_VALIDATION_ERROR, "用户名或密码不能为空");
        }
    }

    /**
     * 保存登录token
     * @param userId
     * @return
     */
    protected String saveLoginToken (Integer userId) {
        //生成登录凭证token，采用UUID（注意UUID随机生成中的-，需要替换掉），因为token必须全局唯一的
        String uuidToken = UUID.randomUUID().toString();
        uuidToken = uuidToken.replace("-","");

        //建立token和用户登录态之间的联系，并设置超时时间为一小时
        redisUtil.set(uuidToken, userId, 3600);
        return uuidToken;
    }
}
